package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Data
public class MSGQueue {
    //队列的唯一身份标识
    private String name;
    //表示队列是否持久化
    private boolean durable;
    //Todo: 表示是否独占
    //true  表示只能为一个消费者使用false 表示为大家都能使用
    private boolean exclusive;
    //todo:自动删除
    private boolean autoDelete = false;
    //todo:参数列表
    private Map<String, Object> arguments = new HashMap<>();
    //表示当前队列都有哪些消费者订阅了
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    //记录当前取到了第几个消费者 方便实现轮询策略
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    //添加一个新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }

    //暂时不考虑订阅者删除
    //挑选一个订阅者 来处理当前的消息
    public ConsumerEnv chooseConsumerEnv() {
        //轮询的方式取
        if (consumerEnvList.size() == 0) {
            //无人订阅
            return null;
        }
        //计算当前下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

}
